package com.qf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.dao.UserDao;
import com.qf.entity.Codes;
import com.qf.entity.User;
import com.qf.exception.ServiceException;
import com.qf.service.UserService;
import com.qf.utils.MD5Utils;
import com.qf.utils.MessageSendingUtils;
import com.qf.utils.CodeUtils;
import com.qf.vo.inputvo.LoginParams;
import org.springframework.stereotype.Service;



import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 用户表(User)表服务实现类
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Resource
    private UserDao userDao;

    /**
     * 用户登录校验
     *
     * @param loginParams
     * @return
     */
    @Override
    public void LoginCheck(LoginParams loginParams) {
        loginParams.setPassword(MD5Utils.str2MD5(loginParams.getPassword()));
        User user = userDao.queryByPhonePassword(loginParams);
        if (user == null) {
            throw new ServiceException(Codes.VERIFY_ERROR);
        }
    }


    /**
     * 发送验证码服务
     * @param loginParams
     * @return
     */
    @Override
    public void CodeSend(LoginParams loginParams){
        //库没查到或者传来的长度为0
        if (userDao.queryByPhone(loginParams.getPhone()) != null) {
            throw new ServiceException(Codes.PHONE_ERROR);

        }
            //生成一个验证码
            Integer code = CodeUtils.createCode();
            //缓存验证码,底部是Map集合在接收
            CodeUtils.setCode(loginParams.getPhone(), code);
            //将验证码发送给登录者
        try {
            MessageSendingUtils.sendMsg(loginParams.getPhone(), String.valueOf(code));
        } catch (Exception e) {
            new ServiceException(Codes.CODESEND_ERROR);
        }

    }


    /**
     * 注册业务
     * @param loginParams
     */
    @Override
    public void Reg(LoginParams loginParams){
        //判定生成的code和前端传回来的code是否相同
        if (Integer.parseInt(loginParams.getCode()) != CodeUtils.getCode(loginParams.getPhone()))
            throw new ServiceException(Codes.CODE_ERROR);

        //将密码加密再放入
        String newPassword =  MD5Utils.str2MD5(loginParams.getPassword());

        User user = new User().setPhone(loginParams.getPhone())
                              .setPassword(newPassword)
                              .setSex(0)
                              .setBirthday(LocalDateTime.now())
                              .setIntegral(0)
                              .setVip(0);

        userDao.insertByPhonePassword(user);
    }


}